package oop.controller.action.exam;

import java.sql.SQLException;

import oop.controller.action.DefaultAction;
import oop.data.Examination;
import oop.data.Test;
import oop.db.dao.ExaminationDAO;
import oop.db.dao.TestDAO;

import com.oreilly.servlet.ParameterNotFoundException;

public class EditAction extends DefaultAction {

	public EditAction() {
	}

	@Override
	public void performImpl() throws Exception {
		try {
			exam = ExaminationDAO.fetchById(getParams().getLong("ee_id"));
			request.setAttribute("exam", exam);
			title("Sửa bài thi " + exam.getName());

			String submit = request.getParameter("ee_submit");
			if ("save".equals(submit)) {
				doEdit();
			}
		} catch (NumberFormatException ex) {
			error("id không hợp lệ");
		}
	}

	private void doEdit() throws SQLException {
		String name;
		try {
			name = getParams().getString("ee_name");
		} catch (ParameterNotFoundException e) {
			nameError = "Bạn cần nhập tên bài kiểm tra.";
			return;
		}
		
		String clazz = request.getParameter("ee_class");
		
		Test test;
		try {
			test = TestDAO.fetchById(getParams().getLong("ee_testid"));
			if (test == null) {
				testError = "Đề thi không tồn tại.";
				return;
			}
		} catch (ParameterNotFoundException ex) {
			testError = "Bạn cần chọn đề thi.";
			return;
		} catch (NumberFormatException ex) {
			testError = "Mã đề thi không hợp lệ.";
			return;
		}

		exam.setName(name);
		exam.setClazz(clazz);
		exam.setTest(test);
		ExaminationDAO.persist(exam);
		setNextAction("exam.view&ev_id=" + exam.getId());
		return;
	}

	private Examination exam;
	private String nameError;
	private String testError;

	public String getNameError() {
		return nameError;
	}
	
	public String getTestError() {
		return testError;
	}
	
}
